package com.powernode.listener;

import com.alibaba.fastjson.JSON;
import com.powernode.config.WxMsgProperties;
import com.powernode.constant.QueueConstant;
import com.powernode.constant.WxConstant;
import com.powernode.model.WxMsgModel;
import com.powernode.service.SmsLogService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 内容:
 * 作者: cy
 */
@Component
public class WxMsgListener {


    @Autowired
    private WxMsgProperties wxMsgProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsLogService smsLogService;


    @RabbitListener(queues = QueueConstant.WX_SEND_QUEUE, concurrency = "3-5")
    public void handlerWxMsg(Message message, Channel channel) {
        String msgStr = new String(message.getBody());
        WxMsgModel wxMsgModel = JSON.parseObject(msgStr, WxMsgModel.class);
        try {
            ResponseEntity<String> result = realSendWxMsg(wxMsgModel);
            // 记录下来
            smsLogService.saveWxMsgLog(wxMsgModel, result);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("人工处理");
        }

    }


    private ResponseEntity<String> realSendWxMsg(WxMsgModel wxMsgModel) {
        String accessToken = redisTemplate.opsForValue().get(WxConstant.WX_TOKEN_KEY);
        String realSendUrl = String.format(wxMsgProperties.getWxMsgUrl(), accessToken);
        ResponseEntity<String> result = restTemplate.postForEntity(realSendUrl, wxMsgModel, String.class);
        System.out.println(result);
        return result;

    }


}
